import { defineStore } from "pinia";
import { ref } from "vue";
import { platformConfigsStorage } from "@/config/storage";
import { detectDevice } from "@/utils/tools";
import { useConfigStore } from "./config";

/** 页面布局信息 */
export const useLayoutStore = defineStore("layout", () => {
    /** 侧边栏配置, 每次屏幕大小变化时或刷新时更新 */
    const sidebar = ref<Sidebar>({
        opened: platformConfigsStorage.value?.SidebarStatus || !!useConfigStore().GET_PLATFORM_CONFIG("SidebarStatus"),
        isClickCollapse: platformConfigsStorage.value?.IsClickCollapse || !!useConfigStore().GET_PLATFORM_CONFIG("IsClickCollapse"), // 是否手动点击Collapse, 用于监控屏幕大小时是否展开侧边栏
    });

    /** 当前的导航模式, 使用 toggleLayout 方法时会存在和平台 config 中的值不一样的情况, 当前的导航模式以此值为准 */
    const layout = ref<Layout>(platformConfigsStorage.value?.Layout || useConfigStore().GET_PLATFORM_CONFIG("Layout") || "vertical");

    /** 设备类型 */
    const device = ref<Device>(detectDevice()); // 检测设备类型, "mobile"|"desktop"

    /** 浏览器视口大小 */
    const viewportSize = ref<ViewportSize>({
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight,
    });

    const setSidebarOpen = (opened: boolean): void => {
        sidebar.value.opened = opened;
        useConfigStore().SET_PLATFORM_CONFIG({ SidebarStatus: opened });
    };

    const toggleSidebarOpen = (): void => {
        sidebar.value.opened = !sidebar.value.opened;
        sidebar.value.isClickCollapse = !sidebar.value.opened; // 标记为手动点击
        useConfigStore().SET_PLATFORM_CONFIG({
            SidebarStatus: sidebar.value.opened,
            IsClickCollapse: sidebar.value.isClickCollapse,
        });
    };

    const toggleDevice = (deviceType: Device): void => {
        device.value = deviceType;
    };

    const toggleLayout = (layoutType: Layout, setOrigin = true): void => {
        layout.value = layoutType;
        if (setOrigin) {
            useConfigStore().SET_PLATFORM_CONFIG({
                Layout: layoutType,
                HiddenSideBar: layoutType === "horizontal", // 水平模式下隐藏侧边栏
            });
        } else {
            // 保留上次的导航模式
            useConfigStore().SET_PLATFORM_CONFIG({
                HiddenSideBar: layoutType === "horizontal",
            });
        }
    };

    const setViewportSize = (width: number, height: number): void => {
        viewportSize.value.width = width;
        viewportSize.value.height = height;
    };

    return {
        layout,
        sidebar,
        device,
        viewportSize,
        setSidebarOpen,
        toggleSidebarOpen,
        toggleDevice,
        toggleLayout,
        setViewportSize,
    };
});
